# 1. Import  standard lib
from flask import render_template, redirect, url_for, flash, request
from uuid import uuid4

# 2. Import bluePrint
from . import main_blueprint

# 3. Used for Init login view
from blog.forms import LoginForm, RegisterForm, OpenIDForm

# 4. Used for Init new `User` instance
from blog.models import User, db

# 5. `extensions` import openid
from blog.extensions import openid

# 6. Used for `login` and `logout` view
from flask_login import login_user, logout_user, current_user


# 7. Used to 
from flask_principal import (
	identity_changed,
	current_app,
	Identity,
	AnonymousIdentity)


# `/login`

@main_blueprint.route('/login', methods=['GET', 'POST'])
@openid.loginhandler
def login():
	#: Init the OpenIDForm
	openid_form = OpenIDForm()
	
	# Send the request for login to relay party(URL)  when click the SUBMIT button
	if openid_form.validate_on_submit():
		return openid.trg_login(
			openid_form.openid_url.data,
			ask_for=['nickname', 'email'],
			ask_for_optional=['fullname'])
	
	#: Try to login the relay party failed
	openid_errors = openid.fetch_error()
	
	if openid_errors:
		flash(openid_errors)
	
	#: Init the LoginForm
	form = LoginForm()	
	
	#: Will be check the accout whether right  when click the SUBMIT button
	if form.validate_on_submit():
		if form.validator():
			#: Keep the user info in the session using Flask-Login
			#: Remember the user's login status
			user = User.query.filter_by(username=form.username.data).first()
			login_user(user, remember=form.remember.data)
			
			#: Principal status send
			#: `identity_changed.send()` will send the single with current_app of identity 
			identity_changed.send(current_app._get_current_object(), identity= Identity(user.id))
			return redirect(url_for('blog.home'))
			
	return render_template('login.html', form=form)


# `/logout`

@main_blueprint.route('/logout', methods=['GET', 'POST'])
def logout():

	#: Remove the user info from the session.
	logout_user()
	
	#: Principal status: `identity_changed.send`
	identity_changed.send(
		current_app._get_current_object(),
		identity=AnonymousIdentity())
		
	return redirect(url_for('main.register'))
 

# `/register`

@main_blueprint.route('/register', methods=['GET', 'POST'])
def register():

	#: Equal to create a html-form object
	form = RegisterForm()	
	#: Will be check the username whether exist when click the SUBMIT button
	if form.validate_on_submit():
		if form.validator():
			#: Create a new user
			new_user = User(id=str(uuid4()), username=form.username.data, password=form.password.data)
			#: commit to database
			db.session.add(new_user)
			db.session.commit()
			flash('Registe succesful, Please login in')
			return redirect(url_for('main.login'))
	
	return render_template('register.html', form=form)


# `/main`

@main_blueprint.route('/')
def main():

	return render_template('main.html')